package prolog.io;
import prolog.terms.Const;
import prolog.terms.Int;
import prolog.terms.Prog;
import prolog.terms.Source;
import prolog.terms.Term;

object CharReader extends Source 
{
  public reader : Reader ;
  class CharReader(f: String,p: Prog) extends Source(p)
	{
	makeReader(f);
	}
  class CharReader(t: Term,p: Prog) extends Source(p)
	{
    this.reader=new StringReader(t.toUnquoted());
	}
  class CharReader(reader: Reader ,p: Prog ) extends Source(p)
	{
     this.reader=reader;
	}
  class CharReader(p: Prog)
	{
     def this(p: Prog)
		{
         this(IO.input,p);
		}
	}
  def makeReader(f: String): unit=
	{
    this.reader=IO.url_or_file(f);
	}
  def getElement() : Term=
	{
	  if(IO.input==reader) 
		{
			var s : String=IO.promptln(">:");
			if(null==s||s.length()==0)
			return null;
			return new Const(s);
		}
    
     if(null==reader)
     return null;
     var c : int=-1;
     try 
		{
		c=reader.read();
		} 
     catch(IOException e)
		{ 
		}
     if(-1==c) 
	 {
      stop();
      return null;
     }
	 else
     return new Int(c);
    }
  
  def stop() : unit=
    {
		if(null!=reader&&IO.input!=reader) 
			{
				try 
					{
					reader.close();
					} 
				catch(IOException e) 
					{ 
					}
				reader=null;
			}
	}
}
